/*
 *  Copyright 2019-2020  Sun Feng
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.ruibo.modules.weixin.service.impl;

import com.ruibo.modules.system.domain.SysDept;
import com.ruibo.modules.system.domain.vo.TreeSelect;
import com.ruibo.modules.system.service.dto.SysDeptDto;
import com.ruibo.modules.system.service.dto.SysMenuDto;
import com.ruibo.modules.weixin.domain.RegionCode;
import com.ruibo.utils.*;
import lombok.RequiredArgsConstructor;
import com.ruibo.modules.weixin.repository.RegionCodeRepository;
import com.ruibo.modules.weixin.service.RegionCodeService;
import com.ruibo.modules.weixin.service.dto.RegionCodeDto;
import com.ruibo.modules.weixin.service.dto.RegionCodeQueryCriteria;
import com.ruibo.modules.weixin.service.mapstruct.RegionCodeMapper;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author 孙峰
 * @website https://el-admin.vip
 * @description 服务实现
 * @date 2020-11-06
 **/
@Service
@RequiredArgsConstructor
public class RegionCodeServiceImpl implements RegionCodeService {

    private final RegionCodeRepository regionCodeRepository;
    private final RegionCodeMapper regionCodeMapper;

    @Override
    public Map<String, Object> queryAll(RegionCodeQueryCriteria criteria, Pageable pageable) {
        Page<RegionCode> page = regionCodeRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return PageUtil.toPage(page.map(regionCodeMapper::toDto));
    }

    @Override
    public List<RegionCodeDto> queryAll(RegionCodeQueryCriteria criteria) {
        return regionCodeMapper.toDto(regionCodeRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    @Transactional

    public RegionCodeDto findById(Long id) {
        RegionCode regionCode = regionCodeRepository.findById(id).orElseGet(RegionCode::new);
        ValidationUtil.isNull(regionCode.getId(), "RegionCode", "id", id);
        return regionCodeMapper.toDto(regionCode);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RegionCodeDto create(RegionCode resources) {
        return regionCodeMapper.toDto(regionCodeRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(RegionCode resources) {
        RegionCode regionCode = regionCodeRepository.findById(resources.getId()).orElseGet(RegionCode::new);
        ValidationUtil.isNull(regionCode.getId(), "RegionCode", "id", resources.getId());
        UpdateUtil.copyNullProperties(resources, regionCode);
        regionCodeRepository.save(regionCode);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            regionCodeRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<RegionCodeDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (RegionCodeDto regionCode : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put(" createdBy", regionCode.getCreatedBy());
            map.put(" createdDate", regionCode.getCreatedDate());
            map.put(" lastModifiedBy", regionCode.getLastModifiedBy());
            map.put(" lastModifiedDate", regionCode.getLastModifiedDate());
            map.put(" remark", regionCode.getRemark());
            map.put(" version", regionCode.getVersion());
            map.put(" parentCode", regionCode.getParentCode());
            map.put(" regionCode", regionCode.getRegionCode());
            map.put(" regionLevel", regionCode.getRegionLevel());
            map.put(" regionName", regionCode.getRegionName());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public List<RegionCodeDto> selectRegionCodeList(RegionCodeQueryCriteria criteria) {

        List<RegionCode> byParentCode = regionCodeRepository.findByParentCode("370000");
        return this.regionCodeMapper.toDto(byParentCode);
    }

    @Override
    public List<RegionCodeDto> getRegionCodeTree(List<RegionCodeDto> regionCodeDtoList) {
        List<RegionCodeDto> list = new LinkedList<>();

        regionCodeDtoList.forEach(regionCodeDto -> {
            LinkedList<RegionCodeDto> childrenList = new LinkedList<>();
            regionCodeDtoList.forEach(regionCodeDto1 -> {
                if (regionCodeDto1.getParentCode().equals(regionCodeDto.getRegionCode())) {
                    childrenList.add(regionCodeDto1);
                }
            });
            if (regionCodeDto.getParentCode().equals("370000")) {
                childrenList.stream().peek(regionCodeDto12 -> regionCodeDto12.setChildren(null));
                regionCodeDto.setChildren(childrenList);
                list.add(regionCodeDto);
            }
        });
        return list;

    }

    @Override
    public List<RegionCodeDto> getRegionCodeTreeWithProvince(List<RegionCodeDto> regionCodeDtoList) {
        List<RegionCodeDto> list = new LinkedList<>();

        regionCodeDtoList.forEach(regionCodeDto -> {
            LinkedList<RegionCodeDto> childrenList = new LinkedList<>();
            regionCodeDtoList.forEach(regionCodeDto1 -> {
                if (regionCodeDto1.getParentCode().equals(regionCodeDto.getRegionCode())) {
                    childrenList.add(regionCodeDto1);
                }
            });
            if (regionCodeDto.getParentCode().equals("000000")) {
                childrenList.stream().peek(regionCodeDto12 -> regionCodeDto12.setChildren(null));
                regionCodeDto.setChildren(childrenList);
                list.add(regionCodeDto);
            }
        });
        return list;
    }


}
